package com.yy.base.common.interceptor;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

public class ExceptionHandler implements HandlerExceptionResolver {

	@Override
	public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex){
		ModelAndView mv = new ModelAndView();
		try {
			ex.printStackTrace();
			String error = ex.getMessage();
			if (ex.getCause() != null) {
				error = ex.getCause().getMessage();
			}
			if (error != null) {
				error = error.replace("\"", "'").replace("\n", "<br/>");
			}
//			error = new String(error.getBytes(), "UTF-8");
			
			response.setStatus(HttpStatus.OK.value()); //设置状态码  
            response.setContentType(MediaType.APPLICATION_JSON_VALUE); //设置ContentType  
            response.setCharacterEncoding("UTF-8"); //避免乱码  
            response.setHeader("Cache-Control", "no-cache, must-revalidate");
            
			PrintWriter writer = response.getWriter();
			writer.write("{\"result\":false,\"status\":\"ERROR\",\"msg\":\"" + error + "\"}");
		} catch (IOException e) {
			e.printStackTrace();
		}
		return mv;
	}
}